package com.hkts.flow.manager.api;



import com.hkts.flow.api.flowableTo.HontRoleTo;
import com.hkts.flow.api.flowableTo.HontUserRoleTo;
import com.hkts.flow.api.flowableTo.HontUserTo;
import com.hkts.flow.core.service.flowable.IFlowableIdentityService;
import com.hkts.flow.feign.FeignInterface;
import com.hkts.flow.manager.utils.Result;
import com.hkts.flow.manager.utils.ResultUtil;
import org.apache.commons.collections.CollectionUtils;
import org.flowable.idm.api.*;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntity;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @ClassNamedataSynchronization
 * @Description 用户机构等模块的数据同步业务
 * @Author yck
 * @Date2020-12-07 15:12
 * @Version V1.0
 **/
@RestController
@RequestMapping("/rest/dataSynchronization")
public class DataSynchronization {
    @Autowired
    private IdmIdentityService idmIdentityService;
    @Autowired
    private IFlowableIdentityService flowableIdentityService;

    @Autowired
    private FeignInterface feignInterface;


    //同步group数据
    @PostMapping("/groupSynchronization")
    @Transactional
    public Result<Object> groupSynchronization() {
        /*
         * 用户同步
         * */
        List<HontUserTo> hontUserTos = feignInterface.fontUserList();
        Integer integer = flowableIdentityService.maxVersion();
        hontUserTos.stream().forEach(hontUserTo -> {
            UserEntityImpl user = new UserEntityImpl();
            List<User> list = idmIdentityService.createUserQuery().userId(hontUserTo.getId()).list();
            long count = idmIdentityService.createUserQuery().userId(hontUserTo.getId()).count();
            user.setDisplayName(hontUserTo.getNickName());
            user.setEmail(hontUserTo.getEmail());
            user.setPassword(hontUserTo.getPassword());
            user.setId(hontUserTo.getId());
            user.setFirstName(hontUserTo.getNickName());
            user.setLastName(hontUserTo.getNickName());

            if (count == 0) {
                user.setRevision(0);
            } else {
                user.setRevision(6);
            }
            if (count == 0) {
                flowableIdentityService.saveUser(user);
                Privilege privilege = idmIdentityService.createPrivilegeQuery().privilegeName("access-idm").singleResult();
                idmIdentityService.addUserPrivilegeMapping(privilege.getId(), user.getId());
            } else {
                flowableIdentityService.updateUserById(user);
            }
        });
        /*
         * j同步
         * */
        List<HontRoleTo> hontRoleTos = feignInterface.fontRoleList();
        //idmIdentityService   GroupEntityImpl
        System.out.println("-------" + hontRoleTos.size() + "-------");
        //
        hontRoleTos.stream().forEach(role -> {
            long count = idmIdentityService.createGroupQuery().groupId(role.getId()).count();
            if (count == 0) {
                GroupEntityImpl group = new GroupEntityImpl();
                group.setName(role.getName());
                group.setId(role.getId());
                group.setRevision(0);
                idmIdentityService.saveGroup(group);
            } else {
                GroupEntityImpl group = new GroupEntityImpl();
                group.setId(role.getId());
                group.setName(role.getName());
                flowableIdentityService.updateGrouprById(group);
            }
        });
        // feignInterface.
        List<HontUserRoleTo> hontRoleTos1 = feignInterface.fontUserRoleList();
        hontRoleTos1.stream().forEach(userRole -> {
            List<User> list = idmIdentityService.createUserQuery().userId(userRole.getHontUserId()).memberOfGroup(userRole.getHontRoleId()).list();
            if (list.size() == 0) {
                idmIdentityService.createMembership(userRole.getHontUserId(), userRole.getHontRoleId());
            }
        });

        return ResultUtil.success("同步成功");
    }
    //数据修改同步group

    /**
     * 添加组成员
     *
     * @return
     */
    @PostMapping("/addGroupUser")
    public Result updateUserGroup(String userId,  String groupIds) {
        UserEntityImpl user = new UserEntityImpl();
        user.setId(userId);
        System.out.println("userId:"+userId);
        System.out.println("groupId:"+groupIds);
        flowableIdentityService.deleteMemberShip(user);
        String[] split = groupIds.split(",");
            for (int i=0;  i < split.length; i++) {
                idmIdentityService.createMembership(userId,split[i]);
            }


        return ResultUtil.success("member成功");
    }
    /*
     * 用户同步
     * */
    @PostMapping("/addUser")
    public Result addUser( HontUserTo user) {
        UserEntityImpl userEntityImpl = new UserEntityImpl();
        userEntityImpl.setRevision(0);
        userEntityImpl.setId(user.getId());
        userEntityImpl.setFirstName(user.getNickName());
        userEntityImpl.setLastName(user.getNickName());
        userEntityImpl.setDisplayName(user.getNickName());
        userEntityImpl.setEmail(user.getEmail());
        userEntityImpl.setPassword(user.getPassword());
        flowableIdentityService.saveUser(userEntityImpl);
        Privilege privilege = idmIdentityService.createPrivilegeQuery().privilegeName("access-idm").singleResult();
        idmIdentityService.addUserPrivilegeMapping(privilege.getId(), user.getId());
        return ResultUtil.success("用户同步成功！");
    }
    /*
     * 用户修改
     * */
    @PostMapping("/updateUser")
    public Result updateUser(HontUserTo user) {
        UserEntityImpl userEntityImpl = new UserEntityImpl();
        userEntityImpl.setRevision(0);
        userEntityImpl.setId(user.getId());
        userEntityImpl.setFirstName(user.getNickName());
        userEntityImpl.setLastName(user.getNickName());
        userEntityImpl.setDisplayName(user.getNickName());
        userEntityImpl.setEmail(user.getEmail());
        flowableIdentityService.updateUserById(userEntityImpl);
        return ResultUtil.success("用户修改同步成功！");
    }

    /*
     *修改组
     * */
    @PostMapping("/updateGroup")
    public Result updateGroup(HontRoleTo hontRoleTo) {
        GroupEntityImpl group = new GroupEntityImpl();
        group.setId(hontRoleTo.getId());
        group.setName(hontRoleTo.getRoleName());
        flowableIdentityService.updateGrouprById(group);
        return ResultUtil.success("组修改同步成功！");
    }

    /**
     * 删除组
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result delete(String id) {
        idmIdentityService.deleteGroup(id);
        return ResultUtil.success("删除成功");
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @PostMapping("/deleteUser")
    public Result deleteUser(String userId) {
        idmIdentityService.deleteUser(userId);

        return ResultUtil.success("删除成功");
    }

}
